﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HomePage.Controllers;
using PortalNews.BUS;
using PortalNews.BlogspotNews;
using PortalNews.WordpressNews;
using Telerik.Web.Mvc;
using WebMatrix.WebData;
using PortalBooking.DAO;
using PortalBooking;
using PortalTicket.DAO;
using PortalAccount;
using MDF.Logger.Managements;
using MDF.Utilites.Helper;
using DataHelper;

namespace TGVR_Project.Controllers
{
    [InitializeSimpleMembership]
    public class AdminController : BaseController
    {
        private int m_TypeNews = 1;
        private int m_PageSize = 20;
        /*
         * 1: Tin hệ thống
         * 2: Tin khuyến mãi
         * 3: Tin thắc mắc
         * 4: Tin giới thiệu
         * 5: Quản lý đặt hàng
         * 6: Vé máy bay quốc tế
         * 7: Vé máy bay nội địa
         * 8: Vé máy bay theo hãng
         * 9: Vé máy bay theo loai
         * 10: Nghiệp vụ
         * 11: Nhượng vé
         * 12: Du lịch
         * */
        //
        // GET: /Admin/
        #region Admin page
        public ActionResult Index()
        {
            if (LoginUser.IsInRole("admin"))
                return ListNewComment(0);
            if (LoginUser.IsInRole("member"))
                return Profile();
            if (!LoginUser.IsInRole("admin") && !LoginUser.IsInRole("member"))
                return Redirect("/account/login");
            return View();
        }

        public AdminController()
            :base()
        {
            
            CommentBUS nComment = new CommentBUS();
            ViewBag.CommentCount = nComment.CountNotRead().ToString();
            ViewBag.NewComment = nComment.GetNewComments();
            UserProfileDAO usrDAo = new UserProfileDAO();

        }
        #region Email nhận tin

        public ActionResult Email(int page = 1)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            EmailRecive[] emails = new PortalNews.DAO.EmailDAO().GetAll();


            var lst = emails;
            this.m_Pagging.Link = "/Admin/Email?page=";
            this.m_Pagging.IsUssing = true;
            this.m_Pagging.CurrentPage = page;
            this.m_Pagging.TotalPage = lst.Length / m_PageSize + (lst.Length % m_PageSize > 0 ? 1 : 0);
            lst = lst.Skip((page - 1) * m_PageSize).Take(m_PageSize).ToArray();

            ViewBag.Emails = lst;

            return View("Email");
        }

        public ActionResult DeleteEmail(string id)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            var emailDAO =new PortalNews.DAO.EmailDAO();
            if (emailDAO.Delete(id.Replace('_','.')))
            {
                this.m_Result.IsSuccess = 1;
                this.m_Result.AddMessage(m_lang.DELETESUCCESS);
            }

            return Email();
        }

        #endregion

        #region Settings
        public ActionResult Setting()
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            SettingDAO sDao = new SettingDAO();
            ViewBag.Settings = sDao.GetAll();
            return View("Setting");
        }
        [HttpPost]
        public ActionResult Setting(Setting[] lstSetting)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            foreach (var item in lstSetting)
            {
                SettingDAO sDao = new SettingDAO();
                if (item.Value != sDao.GetSetting(item.Name))
                    sDao.SetSetting(item.Name, item.Value);
            }
            return Setting();
        }
        #endregion

        #endregion

        #region Booking
        public ActionResult Booking(int page = 1)
        {
            if (!LoginUser.IsInRole("admin") && !LoginUser.IsInRole("member"))
                return Redirect("/account/login");
            var bkDAO = new PortalBooking.DAO.BookingDAO();
            ViewBag.FromDate = DateTime.Now.AddDays(-1);
            ViewBag.ToDate = DateTime.Now;
            var lst = bkDAO.Get();
            if (LoginUser.IsInRole("member"))
                lst = lst.Where(m => m.UserId == LoginUser.INFO.UserId).ToArray();

            this.m_Pagging.Link = "/Admin/Booking?page=";
            this.m_Pagging.IsUssing = true;
            this.m_Pagging.CurrentPage = page;
            this.m_Pagging.TotalPage = lst.Length / m_PageSize + (lst.Length % m_PageSize > 0 ? 1 : 0);
            lst = lst.Skip((page - 1) * m_PageSize).Take(m_PageSize).ToArray();

            return View("Booking", lst);
        }
        [GridAction]
        public ActionResult _Booking()
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            var bkDAO = new PortalBooking.DAO.BookingDAO();
            //var lst = bkDAO.Get().Where(m => m.CreatedDate > FromDate && m.CreatedDate < ToDate);
            var lst = bkDAO.Get().Select(m => new
            {
                m.Address,
                m.CreatedDate,
                m.Email,
                m.FromCity,
                m.ID,
                m.IP,
                m.Name,
                m.Note,
                m.Phone,
                m.SessionID,
                m.Status,
                m.ToCity,
                m.TotalPrice,
                m.Ways,
                m.Amount,
                m.FlightDepart,
                m.FlightReturn
            });
            return View("_Booking", new GridModel(lst));
        }
        [GridAction]
        public ActionResult _OrderTicket()
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            var lst = new OrderDAO().GetAll();
            return View("_OrderTicket", new GridModel(lst));
        }

        [GridAction]
        public ActionResult OrderTicket(int page = 1)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            var lst = new OrderDAO().GetAll();

            this.m_Pagging.Link = "/Admin/OrderTicket?page=";
            this.m_Pagging.IsUssing = true;
            this.m_Pagging.CurrentPage = page;
            this.m_Pagging.TotalPage = lst.Length / m_PageSize + (lst.Length % m_PageSize > 0 ? 1 : 0);
            lst = lst.Skip((page - 1) * m_PageSize).Take(m_PageSize).ToArray();

            return View("OrderTicket", lst);
        }

        public ActionResult DeleteBooking(string id)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            BookingDAO nBooking = new BookingDAO();
            if (nBooking.Delete(Int32.Parse(id)))
            {
                m_Result.AddMessage(m_lang.SUCCESS);
                m_Result.IsSuccess = 1;
            }
            return Booking();
        }

        #endregion

        public ActionResult BookingDetail(string id)
        {
            if (!LoginUser.IsInRole("admin") && !LoginUser.IsInRole("member"))
                return Redirect("/account/login");
            TicketDAO tDAo = new TicketDAO();
            var lstTickets = tDAo.GetByBookingID(Int32.Parse(id));

            BookingDAO bkDAO = new BookingDAO();

            var booing = bkDAO.Get(Int32.Parse(id));
            ViewBag.booing = booing;
            BookingDetailDAO bdDAO = new BookingDetailDAO();
            var lstBookingDetails = bdDAO.Get(Int32.Parse(id));

            ViewBag.BookingDetails = lstBookingDetails;
            ViewBag.Tickets = tDAo.Convert(lstTickets);
            return View();
        }

        #region Setting
        public ActionResult Setting_Discount()
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            PortalTicket.DAO.SettingDAO sDAO = new PortalTicket.DAO.SettingDAO();
            ViewBag.Discount = sDAO.GetDiscount();
            return View();
        }

        [HttpPost]
        public ActionResult Setting_Discount(int iDiscount)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            PortalTicket.DAO.SettingDAO sDAO = new PortalTicket.DAO.SettingDAO();
            if (sDAO.SetDiscount(iDiscount))
            {
                this.m_Result.IsSuccess = 1;
                this.m_Result.AddMessage(m_lang.SUCCESS);
                ViewBag.Discount = sDAO.GetDiscount();
            }
            return View();
        }
        #endregion

        #region Process pages comment

        public ActionResult ListComment(int page = 1)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            CommentBUS nComment = new CommentBUS();

            var lst = nComment.GetAll();
            this.m_Pagging.Link = "/Admin/ListComment?page=";
            this.m_Pagging.IsUssing = true;
            this.m_Pagging.CurrentPage = page;
            this.m_Pagging.TotalPage = lst.Length / m_PageSize + (lst.Length % m_PageSize > 0 ? 1 : 0);
            lst = lst.Skip((page - 1) * m_PageSize).Take(m_PageSize).ToArray();

            return View("ListComment", lst);
        }
        [GridAction]
        public ActionResult _ListComment()
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            CommentBUS nComment = new CommentBUS();
            return View("_ListComment", new GridModel(nComment.GetAll()));
        }
        public ActionResult DeleteComment(string id)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            CommentBUS nComment = new CommentBUS();
            if (nComment.Delete(id))
            {
                m_Result.AddMessage(m_lang.SUCCESS);
                m_Result.IsSuccess = 1;
            }
            return ListComment();
        }

        public ActionResult ListNewComment(int page = 1)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            CommentBUS nComment = new CommentBUS();
            var lst = nComment.GetNewComments();
            this.m_Pagging.Link = "/Admin/ListNewComment?page=";
            this.m_Pagging.IsUssing = true;
            this.m_Pagging.CurrentPage = page;
            this.m_Pagging.TotalPage = lst.Length / m_PageSize + (lst.Length % m_PageSize > 0 ? 1 : 0);
            lst = lst.Skip((page - 1) * m_PageSize).Take(m_PageSize).ToArray();
            return View("ListNewComment", lst);
        }
        [GridAction]
        public ActionResult _ListNewComment()
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            CommentBUS nComment = new CommentBUS();
            var temp = nComment.GetNewComments();
            //if(temp==null)
            //   temp=new Comment[0];
            return View("_ListNewComment", new GridModel(temp));
        }
        #endregion

        #region Process pages News
        public ActionResult ListNews(string strAction = "ListNews", int page = 1)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            ViewData["strController"] = strAction;
            NewsBUS nBus = new NewsBUS();
            var lstData = nBus.GetAll(m_TypeNews);
            string keyword = "";
            if (Request["keyword"] != null)
            {
                keyword = Request["keyword"].ToString();
                keyword = StringHelper.ToNonUnicode(keyword.Trim().ToLower());
                lstData = lstData.Where(m => StringHelper.ToNonUnicode(m.Title.ToLower()).IndexOf(keyword) > -1).ToArray();
            }

            var lst = lstData;
            this.m_Pagging.Link = "/Admin/" + strAction + "?keyword=" + keyword + "&page=";
            this.m_Pagging.IsUssing = true;
            this.m_Pagging.CurrentPage = page;
            this.m_Pagging.TotalPage = lst.Length / m_PageSize + (lst.Length % m_PageSize > 0 ? 1 : 0);
            lst = lst.Skip((page - 1) * m_PageSize).Take(m_PageSize).ToArray();

            return View("ListNews", lst);
        }

        [GridAction]
        public ActionResult _ListNews()
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            NewsBUS nBus = new NewsBUS();
            return View("_ListNews", new GridModel(nBus.GetAll(m_TypeNews)));
        }

        public ActionResult DeleteNews(string id, string typeID = "1")
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            NewsBUS nBus = new NewsBUS();
            if (nBus.Delete(id))
            {
                m_Result.AddMessage(m_lang.SUCCESS);
                m_Result.IsSuccess = 1;
            }
            m_TypeNews = Int32.Parse(typeID);
            return ListNews();
        }
        public ActionResult DeleteOrder(string id)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            OrderDAO nBus = new OrderDAO();
            if (nBus.Delete(Int32.Parse(id)))
            {
                m_Result.AddMessage(m_lang.SUCCESS);
                m_Result.IsSuccess = 1;
            }
            return OrderTicket();
        }
        public ActionResult EditNews(string id)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            New[] arrNews = new New[2];
            NewsBUS nBUS = new NewsBUS();
            int iNews = Int32.Parse(id);
            arrNews[0] = nBUS.GetByID(iNews, 1);
            arrNews[1] = nBUS.GetByID(iNews, 2);
            ViewBag.arrNews = arrNews;
            ViewData["autoUpload"] = true;
            ViewData["multiple"] = true;
            return View("CreateNews");
        }
        [ValidateInput(false)]
        public ActionResult CreateNews(New[] arrNews)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            if (arrNews == null)
            {
                arrNews = new New[2];
                arrNews[0] = new New();
                arrNews[1] = new New();
                arrNews[0].LangID = 1;
                arrNews[1].LangID = 2;
                arrNews[0].TypeID = m_TypeNews;
                arrNews[1].TypeID = m_TypeNews;
            }
            else
            {
                NewsBUS nBus = new NewsBUS();

                //arrNews[0].IsPin
                arrNews[0].IsPin = Request.Form["arrNews[0].IsPin"] != null;
                arrNews[1].IsPin = Request.Form["arrNews[1].IsPin"] != null;

                //return null;
                
                if (Request.Files["ImageFile1"] != null)
                {
                    string strTemp = this.SaveFile(Request.Files["ImageFile1"]);
                    if (strTemp.Length > 3)
                    {
                        arrNews[0].Image = strTemp;
                    }
                }
                if (Request.Files["ImageFile2"] != null)
                {
                    string strTemp = this.SaveFile(Request.Files["ImageFile2"]);
                    if (strTemp.Length > 3)
                    {
                        arrNews[1].Image = strTemp;
                    }
                }

                if (arrNews[0].ID == 0)
                {
                    if (nBus.Insert(arrNews[0], arrNews[1]))
                    {
                        arrNews[0].LangID = 1;
                        arrNews[1].LangID = 2;
                        #region Post to social pages
                        try
                        {
                            BlogPoster.AddPost(arrNews[0].Title, arrNews[0].Content, arrNews[0].SEO.Split(','));
                        }
                        catch (Exception ex)
                        {
                            LogManager.GetInstance().Warning("Admin: CreateNews: Cant not post to BlogPoster VN",ex);
                        }
                        try
                        {
                            BlogPoster.AddPost(arrNews[1].Title, arrNews[1].Content, arrNews[1].SEO.Split(','));
                        }
                        catch (Exception ex)
                        {
                            LogManager.GetInstance().Warning("Admin: CreateNews: Cant not post to BlogPoster EN",ex);
                        }
                        try
                        {
                            new WordpressPoster().AddPost(arrNews[0].Title, arrNews[0].Content, arrNews[0].SEO.Split(','));
                        }
                        catch (Exception ex)
                        {
                            LogManager.GetInstance().Warning("Admin: CreateNews: Cant not post to WordpressPoster VN", ex);
                        }
                        try
                        {
                            new WordpressPoster().AddPost(arrNews[1].Title, arrNews[1].Content, arrNews[1].SEO.Split(','));
                        }
                        catch (Exception ex)
                        {
                            LogManager.GetInstance().Warning("Admin: CreateNews: Cant not post to WordpressPoster EN", ex);
                        }
                        #endregion
                        arrNews = new New[2];
                        arrNews[0] = new New();
                        arrNews[1] = new New();
                        arrNews[0].LangID = 1;
                        arrNews[1].LangID = 2;
                        arrNews[0].TypeID = m_TypeNews;
                        arrNews[1].TypeID = m_TypeNews;
                        m_Result.AddMessage(m_lang.SUCCESS);
                        m_Result.IsSuccess = 1;
                    }
                    else
                    {
                        m_Result.AddMessage(m_lang.NOTSUCCESS);
                        m_Result.IsSuccess = -1;
                    }
                }
                else
                {
                    if (nBus.Update(arrNews[0], arrNews[1]))
                    {
                        m_Result.AddMessage(m_lang.SUCCESS);
                        m_Result.IsSuccess = 1;
                    }

                    else
                    {
                        m_Result.AddMessage(m_lang.NOTSUCCESS);
                        m_Result.IsSuccess = -1;
                    }
                }
            }
            ViewBag.arrNews = arrNews;
            ViewData["autoUpload"] = true;
            ViewData["multiple"] = true;
            return View("CreateNews");
        }
        #endregion

        #region Sale news
        public ActionResult CreateSaleNews()
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            m_TypeNews = 2;
            return CreateNews(null);
        }

        public ActionResult ListSaleNews(int page = 1)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            m_TypeNews = 2;
            return ListNews("ListSaleNews", page);
        }
        #endregion

        #region  QuestionNews
        public ActionResult CreateQuestionNews()
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            m_TypeNews = 3;
            return CreateNews(null);
        }

        public ActionResult ListQuestionNews(int page = 1)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            m_TypeNews = 3;
            return ListNews("ListQuestionNews", page);
        }
        #endregion

        #region  AboutUs
        public ActionResult CreateAboutUsNews()
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            m_TypeNews = 4;
            return CreateNews(null);
        }

        public ActionResult ListAboutUsNews(int page = 1)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            m_TypeNews = 4;
            return ListNews("ListAboutUsNews", page);
        }

        #endregion

        #region  PurchaseNews
        public ActionResult CreatePurchaseNews()
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            m_TypeNews = 5;
            return CreateNews(null);
        }

        public ActionResult ListPurchaseNews(int page = 1)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            m_TypeNews = 5;
            return ListNews("ListPurchaseNews", page);
        }
        #endregion

        #region  InterTicketNews
        public ActionResult CreateInterTicketNews()
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            m_TypeNews = 6;
            return CreateNews(null);
        }

        public ActionResult ListInterTicketNews(int page = 1)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            m_TypeNews = 6;
            return ListNews("ListInterTicketNews", page);
        }
        #endregion

        #region  DomesticTicketNews
        public ActionResult CreateDomesticTicketNews()
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            m_TypeNews = 7;
            return CreateNews(null);
        }

        public ActionResult ListDomesticTicketNews(int page = 1)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            m_TypeNews = 7;
            return ListNews("ListDomesticTicketNews", page);
        }
        #endregion

        #region  FirmTicketNews
        public ActionResult CreateFirmTicketNews()
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            m_TypeNews = 8;
            return CreateNews(null);
        }

        public ActionResult ListFirmTicketNews(int page = 1)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            m_TypeNews = 8;
            return ListNews("ListFirmTicketNews", page);
        }
        #endregion

        #region  TypeTicketNews
        public ActionResult CreateTypeTicketNews()
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            m_TypeNews = 9;
            return CreateNews(null);
        }

        public ActionResult ListTypeTicketNews(int page = 1)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            m_TypeNews = 9;
            return ListNews("ListTypeTicketNews", page);
        }
        #endregion

        #region  OurworkNews
        public ActionResult CreateOurworkNews()
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            m_TypeNews = 10;
            return CreateNews(null);
        }

        public ActionResult ListOurworkNews(int page = 1)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            m_TypeNews = 10;
            return ListNews("ListOurworkNews", page);
        }
        #endregion

        #region  ReSale
        public ActionResult CreateResaleNews()
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            m_TypeNews = 11;
            return CreateNews(null);
        }

        public ActionResult ListReSaleNews(int page = 1)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            m_TypeNews = 11;
            return ListNews("ListReSaleNews", page);
        }
        #endregion

        #region  Travel
        public ActionResult CreateTravelNews()
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            m_TypeNews = 12;
            return CreateNews(null);
        }

        public ActionResult ListReTravelNews(int page = 1)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            m_TypeNews = 12;
            return ListNews("ListReTravelNews", page);
        }
        #endregion

        #region Management Retail
        public ActionResult CreateRetail()
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            UserProfile usrProfile = new UserProfile();
            return View(usrProfile);
        }
        //firstname=&lastname=&email=ducngo&password=abc123&password_again=&dd=&mm=&yyyy=&zipcode=&city=#
        [HttpPost]
        public ActionResult CreateRetail(string name, string email, string password, int dd, int mm, int yyyy, string zipcode, string address, string sex, string phone)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            //WebSecurity.CreateUserAndAccount(email, password);
            UserProfile usrProfile = new UserProfile();
            using (AccountDataContext context = new AccountDataContext())
            {
                try
                {
                    context.Connection.Open();
                    context.Transaction = context.Connection.BeginTransaction();
                    UserProfileDAO usrDAO = new UserProfileDAO(context);

                    
                    usrProfile.UserName = email;
                    usrProfile.Name = name;
                    usrProfile.Email = email;
                    usrProfile.Address = address;
                    usrProfile.IsDeleted = false;
                    usrProfile.IsLocked = false;
                    usrProfile.Sex = sex;
                    usrProfile.Birthday = new DateTime(yyyy, mm, dd);
                    usrProfile.Phone = phone;
                    usrProfile.CreatedDate = DateTime.Now;
                    Random r = new Random();
                    usrProfile.Avatar="/Content/Images/avarta/av"+r.Next(0,10)+".png";

                    int iUserId = usrDAO.Insert(usrProfile);

                    UserMembership usrSystem = new UserMembership();
                    usrSystem.IsConfirmed = false;
                    usrSystem.IsDeleted = false;
                    usrSystem.CreateDate = DateTime.Now;
                    usrSystem.Password = password;
                    usrSystem.UserId = iUserId;
                    usrSystem.PasswordSalt = "";

                    UserMembershipDAO usrSystemDAO = new UserMembershipDAO(context);
                    usrSystemDAO.Insert(usrSystem);

                    UsersInRolesDAO roleDAO = new UsersInRolesDAO(context);

                    roleDAO.AddToRole(iUserId, 2);

                    context.Transaction.Commit();
                }
                catch (Exception ex)
                {
                    context.Transaction.Rollback();
                    LogManager.GetInstance().Error("Tạo đại lý thất bại", ex);
                }
                finally
                {
                    context.Connection.Close();
                }
            }

            return View(usrProfile);
        }

        public ActionResult RetailList(int page = 1)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            UserProfileDAO usrDAO = new UserProfileDAO();

            var temp = usrDAO.Get();

            var lst = temp.Where(m => m.UserInRoles.SingleOrDefault() != null && m.UserInRoles.SingleOrDefault().RoleId == 2).ToArray();
            this.m_Pagging.Link = "/Admin/RetailList?page=";
            this.m_Pagging.IsUssing = true;
            this.m_Pagging.CurrentPage = page;
            this.m_Pagging.TotalPage = lst.Length / m_PageSize + (lst.Length % m_PageSize > 0 ? 1 : 0);
            lst = lst.Skip((page - 1) * m_PageSize).Take(m_PageSize).ToArray();

            return View("RetailList",lst);
        }

        public ActionResult MemberDetail(string id)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            UserProfileDAO usrDAO=new UserProfileDAO();
            var user = usrDAO.Get(Int32.Parse(id));
            return Profile(new PortalUser( user));
        }

        public ActionResult DeleteRetail(string id)
        {
            if (!LoginUser.IsInRole("admin"))
                return Redirect("/account/login");
            UserProfileDAO usrDAO=new UserProfileDAO();
            usrDAO.Delete(Int32.Parse(id));
            this.m_Result.IsSuccess = 1;
            this.m_Result.AddMessage(m_lang.SUCCESS);
            return RetailList();
        }

        


        #endregion

        #region Profile

        public ActionResult Profile(PortalUser userObj= null)
        {
            if (!LoginUser.IsInRole("admin") && !LoginUser.IsInRole("member"))
                return Redirect("/account/login");
            if (userObj == null || userObj.INFO==null)
                userObj = LoginUser;
            return View("Profile", userObj);
        }

        public ActionResult ChangeInfo()
        {
            if (!LoginUser.IsInRole("admin") && !LoginUser.IsInRole("member"))
                return Redirect("/account/login");
            return View("CreateRetail", LoginUser.INFO);
        }
        [HttpPost]
        public ActionResult ChangeInfo(string name, int dd, int mm, int yyyy, string zipcode, string address, string sex, string phone)
        {
            if (!LoginUser.IsInRole("admin") && !LoginUser.IsInRole("member"))
                return Redirect("/account/login");

            using (AccountDataContext context = new AccountDataContext())
            {
                try
                {
                    context.Connection.Open();
                    UserProfileDAO usrDAO = new UserProfileDAO(context);

                    UserProfile usrProfile = usrDAO.Get(LoginUser.INFO.UserName);
                    usrProfile.Name = name;
                    usrProfile.Address = address;
                    usrProfile.Sex = sex;
                    usrProfile.Birthday = new DateTime(yyyy, mm, dd);
                    usrProfile.Phone = phone;

                    if (Request.Files.Count > 0)
                    {
                        string strTemp = this.SaveFile(Request.Files[0], 150, 150);
                        if (strTemp.Length > 3)
                            usrProfile.Avatar = strTemp;
                    }
                    usrDAO.Update(usrProfile);
                    LoginUser.INFO = usrProfile;
                    return Redirect("/Admin/Profile");
                }
                catch (Exception ex)
                {

                }
            }

            return View("CreateRetail", LoginUser.INFO);
        }

        public ActionResult ChangePassword()
        {
            if (!LoginUser.IsInRole("admin") && !LoginUser.IsInRole("member"))
                return Redirect("/account/login");
            return View();
        }
        //LocalPasswordModel model
        [HttpPost]
        public ActionResult ChangePassword(TGVR_Project.Models.LocalPasswordModel model)
        {
            if (!LoginUser.IsInRole("admin") && !LoginUser.IsInRole("member"))
                return Redirect("/account/login");
            UserMembershipDAO usrSystemDAO = new UserMembershipDAO();
            UserMembership usrSystem = usrSystemDAO.Get(LoginUser.INFO.UserId);
            if (usrSystem.Password == model.OldPassword)
            {
                usrSystem.Password = model.NewPassword;
                usrSystemDAO.Update(usrSystem);
                this.m_Result.IsSuccess = 1;
                this.m_Result.AddMessage(m_lang.UPDATESUCESS);
            }
            else
            {
                this.m_Result.IsSuccess = -1;
                this.m_Result.AddMessage(m_lang.UPDATEFAILED);
                this.m_Result.AddMessage(m_lang.PASSWORDOLDNOTMATCH);
            }
            return View();
        }


        #endregion

    }
}
